package network.盗版qq.qqclient.service;

import network.盗版qq.comment.Message;
import network.盗版qq.comment.MessageType;
import network.盗版qq.comment.User;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;


/**
 * @author mubei
 * @date 2021/12/6
 * @description 登录验证和用户注册等功能
 */
public class UserClientService {


    // 多个方法
    private User user = new User();

    private Socket socket;

    /*
     *
     * */
    public boolean checkUser(String userId, String pwd) {
        boolean result = false;
        //  设置传出的user对象
        user.setUserId(userId);
        user.setPassword(pwd);


        // 发送user对象到服务器
        try {
            socket = new Socket(InetAddress.getLocalHost(), 9999);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(user);

            //接收读取的反馈信息
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message message = (Message) ois.readObject();

            if (message.getMesType() == MessageType.LOGIN_SUCCEED) {
                // 登录成功
                result = true;
                // 创建一个和服务器端保持通信的线程类  创建一个线程类
                ClientConnectServerThread clientConnectServerThread = new ClientConnectServerThread(socket);
                new Thread(() -> {
                    clientConnectServerThread.run();
                }).start();
                // 将线程加入 管理器
                ManageClientConnectServer.addClientConnectServerThread(userId, clientConnectServerThread);

            } else {
                // 登录失败
                socket.close();
                result = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    // 向服务器端请求在线用户列表
    public void onLineFriendList()  {

        // 发送一个message
        Message message = new Message();
        message.setMesType(MessageType.GET_ONLINE_FRIEND);
        message.setSender(user.getUserId());

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void clientExit(){
        // 发送一个message
        Message message = new Message();
        message.setMesType(MessageType.CLIENT_EXIT);
        message.setSender(user.getUserId());

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
            System.out.println(user.getUserId()+" 退出系统");
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
